package com.es.gateway.sdk.app.rpverify_h5_ext;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.*;
import java.security.spec.*;

/*
 * ECC256工具类
 */
public class ECC256Util {
    public static final String KEY_ALGORITHM = "EC";
    public static final String SIGNATURE_ALGORITHM = "SHA256withECDSA";

    /**
     * ECC验签
     * @param response 被签名原始数据
     * @param sign 签名数据
     * @param pubkey 公钥(eFaceID  H5版公钥为: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWKKJoLwh6XEBkTeCfVbKSB3zkkycbIdd8SBabj2jpWynXx0pBZvdFpbb9AEiyrnM8bImhpz8YOXc2yUuN1ui/w== )
     * @return true:验签成功, false: 验签失败
     */
    public static boolean verify(String response, String sign, String pubkey) {
        boolean verifyResult = false;
        byte[] publicKeyBuff = Base64.decodeBase64(pubkey);
        byte[] signatureBuff = Base64.decodeBase64(sign);

        Security.addProvider(new BouncyCastleProvider());
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKeyBuff);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicKey);
            signature.update(response.getBytes());
            verifyResult = signature.verify(signatureBuff);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            return verifyResult;
        }
    }
}